package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.KillConstants;
import cn.itsource.ymcc.constant.PayConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.dto.PreOrderDto;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import cn.itsource.ymcc.service.ICourseOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Slf4j
@Component
//consumerGroup = 定义组
//topic = 主题
//selectorExpression = tag
@RocketMQMessageListener(
        consumerGroup = "OrderKillConsumer",
        topic = KillConstants.TOPIC_ORDER_TIMEOUT,
        selectorExpression = KillConstants.TAGS_ORDER_TIMEOUT
)
public class OrderKillConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            //得到消息
            byte[] body = messageExt.getBody();
            //转为字符串  -- json字符串
            String killOrderSn = new String(body, Constants.UTF8);
            //验证 用户有没有----付钱
            CourseOrder one = courseOrderService.getOne(new QueryWrapper<CourseOrder>()
                    .eq("order_no", killOrderSn)
                    .eq("status_order", RConst.Num.INT_1));
            if(one == null){//没有给钱
                //删除redis里面的数据    你的库存要加回来吗？
                PreOrderDto preOrderDto = (PreOrderDto) redisTemplate.opsForValue()
                        .get(KillConstants.KEY_PREFIX_PRE_ORDER + ":" + killOrderSn);
                Integer count = preOrderDto.getCount();//我秒杀的数量
                //直接追加回去
                redisTemplate.opsForValue()
                        .increment(KillConstants.KILL_STORE+":"+preOrderDto.getKillCourseId(),count);

            }
            //清除一些缓存数据   删除伪订单
            redisTemplate.delete(KillConstants.KEY_PREFIX_PRE_ORDER+":"+killOrderSn);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
